package com.xwj.service.holder;

import com.alibaba.fastjson.JSON;
import com.xwj.entity.RaRole;
import com.xwj.entity.RaRoleRoot;
import com.xwj.entity.RaRoot;
import com.xwj.service.Impl.RaRoleRootServiceImpl;
import com.xwj.service.Impl.RaRoleServiceImpl;
import com.xwj.service.Impl.RaRootServiceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by xuweijie on 2018/2/7.
 */
public class RaRoleHolder {

    public static List<RaRole> getRole() {
        List<RaRole> roleList = RaRoleServiceImpl.getInstance().findAllRole();
        roleList.forEach(role -> {
            List<RaRoleRoot> raRoleRootList = RaRoleRootServiceImpl.getInstance().findRoleRootByRoleId(role.getId());
            if (raRoleRootList.size() > 0) {
                List<Integer> rootIds = raRoleRootList.stream().map(RaRoleRoot::getRootid).collect(Collectors.toList());
                List<RaRoot> raRootList = RaRootServiceImpl.getInstance().findRootByIds(rootIds);
                if (raRootList.size() > 0)
                    role.setRaRoots(raRootList);
            }
            role.setJsonString(JSON.toJSONString(role));
        });
        return roleList;
    }

    public static void deleteRoleById(int roleId) {
        RaRoleServiceImpl.getInstance().deleteRoleById(roleId);
        RaRoleRootServiceImpl.getInstance().deleteAllRoot(roleId);
    }

    public static boolean addRoleInfo(String name, String desc, List<Integer> roots) {
        int id = RaRoleServiceImpl.getInstance().addRole(name, desc);
        if (id != 0) {
            if (roots != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("roleId", id);
                map.put("list", roots);
                RaRoleRootServiceImpl.getInstance().insertRoleRoot(map);
            }
            return true;
        }
        return false;
    }

}
